<?php
/**
 * Created by PhpStorm.
 * User: MADAO
 * Date: 2019/9/28
 * Time: 11:37
 */

namespace App\Services;

use App\Helps\Server as HelpsServer;
use App\Model\GroupRecord;
use App\Model\SecretRecord;
use App\Tasks\BroadcastTask;
use Hyperf\DbConnection\Db;
use Hyperf\Task\Task;
use Hyperf\Task\TaskExecutor;
use Hyperf\Utils\ApplicationContext;
use Swoole\WebSocket\Server;

class ChatService
{
    /**
     * @property-read string $fdMapUserId
     */
    public $fdMapUserId = 'fdMapUserId';
    /**
     * @property-read string $userIdMapFd
     */
    public $userIdMapFd = 'userIdMapFd';

    public function secretChat(Server $server, int $fd, $data)
    {
        $container = ApplicationContext::getContainer();
        $redis = $container->get(\Redis::class);
        $fd = $redis->hGet($this->userIdMapFd, (string)$data['acceptUserId']);

        //todo 判断是否在线
        $server->push((int)$fd, json_encode(['data' => [
            'message' => $data['message'],
            'userId' => $data['senderUserId'],
        ], 'channel' => __FUNCTION__]));

        SecretRecord::query()->create([
            'sender_user_id' => $data['senderUserId'],
            'accept_user_id' => $data['acceptUserId'],
            'raw_data' => $data['message']
        ]);
    }

    public function groupChat(Server $server, int $fd, $data)
    {
        $userIds = Db::table('user_chat_room')->where(['chat_room_id' => $data['roomId']])
            ->pluck('user_id')->map(function ($item) {
                return (string)$item;
            })->toArray();

        $container = ApplicationContext::getContainer();
        $redis = $container->get(\Redis::class);
        $fds = $redis->hMGet('userIdMapFd', $userIds); //发送给所有的用户

        $sendData = [
            'data' => [
                'userId' => $data['userId'],
                'roomId' => $data['roomId'],
                'message' => $data['message'],
            ],
            'channel' => __FUNCTION__
        ];
        $task = $container->get(TaskExecutor::class);
        $task->execute(new Task([BroadcastTask::class, 'handle'], [$sendData, $fd, $fds]));

        GroupRecord::query()->create([
            'chat_room_id' => $data['roomId'],
            'user_id' => $data['userId'],
            'raw_data' => $data['message']
        ]);
    }

    /**
     * 获取webSocket的连接
     * @return array
     */
    public function getConnections(): array
    {
        $fds = [];
        $port = HelpsServer::webSocketServerPort();
        foreach ($port->connections as $connection) {
            $fds[] = (string)$connection;
        }
        return $fds;
    }
}
